/*
 * Copyright (c) 2018-2999 九五云信息科技有限公司 All rights reserved.
 *
 * https://www.gz-yami.com/
 *
 * 未经允许，不可做商业用途！
 *
 * 版权所有，侵权必究！
 */

package com.yami.shop.api.controller;

import com.alipay.api.AlipayApiException;
import com.github.binarywang.wxpay.exception.WxPayException;
import com.yami.shop.bean.bo.PayInfoBo;
import com.yami.shop.common.enums.PayType;
import com.yami.shop.bean.model.Order;
import com.yami.shop.bean.model.OrderItem;
import com.yami.shop.common.i18n.I18nMessage;
import com.yami.shop.common.i18n.LanguageEnum;
import com.yami.shop.service.PayManagerService;
import com.yami.shop.service.PayService;
import com.yami.shop.service.ProductService;
import com.yami.shop.service.SkuService;
import lombok.AllArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.util.List;

@ApiIgnore
@RestController
@RequestMapping("/notice/pay")
@AllArgsConstructor
public class PayNoticeController {

    private final PayService payService;

    private final ProductService productService;

    private final SkuService skuService;

    private final PayManagerService payManagerService;



    /**
     * 支付异步回调
     */
    @RequestMapping("/order/{payType}")
    public ResponseEntity<String> submit(HttpServletRequest request, @PathVariable Integer payType, @RequestBody(required = false) String xmlData) throws WxPayException, UnsupportedEncodingException, AlipayApiException {


        PayInfoBo payInfoBo = payManagerService.validateAndGetPayInfo(request,PayType.instance(payType),xmlData);

        // 根据内部订单号更新order settlement
        List<Order> orders = payService.paySuccess(payInfoBo.getPayNo(), payInfoBo.getBizPayNo(),payType);

        // 移除缓存
        for (Order order : orders) {
            List<OrderItem> orderItems = order.getOrderItems();
            for (OrderItem orderItem : orderItems) {
                productService.removeProdCacheByProdId(orderItem.getProdId(),LanguageEnum.LANGUAGE_ZH_CN.getLang());
                productService.removeProdCacheByProdId(orderItem.getProdId(),LanguageEnum.LANGUAGE_EN.getLang());
                skuService.removeSkuCacheBySkuIdAndLang(orderItem.getSkuId(),orderItem.getProdId(),LanguageEnum.LANGUAGE_ZH_CN.getLang());
                skuService.removeSkuCacheBySkuIdAndLang(orderItem.getSkuId(),orderItem.getProdId(),LanguageEnum.LANGUAGE_EN.getLang());
            }
        }

        return ResponseEntity.ok(payInfoBo.getSuccessString());
    }

}
